﻿/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using TeachMe.Application.Configuration;
using TeachMe.Application.Properties;

namespace TeachMe.Application.Forms
{
    public partial class OnlineDictsForm : PseudoModalForm
    {
        public class OnlineDicts
        {
            [XmlArrayItem("Item")]
            public List<OnlineDictDescriptor> Items { get; set; }
        }

        private List<OnlineDictDescriptor> _dicts = new List<OnlineDictDescriptor>();
        private readonly Root _root;

        public OnlineDictsForm(Root root)
        {
            _root = root;

            InitializeComponent();

            onlineDictsBindingSource.DataSource = _dicts;

            WindowProportions.Lock(this, _root.MachineSettings);
            GridProportions.Lock(this, grid, _root.MachineSettings);
        }

        public IEnumerable<OnlineDictDescriptor> Result
        {
            get
            {
                return this.GetSelection();
            }
        }

        public void Display(WebContentDownloader<OnlineDicts, object>.Job[] jobs)
        {
            onlineDictsBindingSource.Clear();

            OnlineDicts onlineDicts = jobs[0].Result;

            if (onlineDicts == null)
            {
                MessageBox.Show(Resources.OnlineCheckFailed, Resources.MessageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // temporary language fix
            foreach (OnlineDictDescriptor item in onlineDicts.Items)
            {
                if (Singleton<Languages>.Instance.GetByCode(item.From) != null)
                {
                    item.From = Singleton<Languages>.Instance.GetByCode(item.From).Localized;
                }
                if (Singleton<Languages>.Instance.GetByCode(item.To) != null)
                {
                    item.To = Singleton<Languages>.Instance.GetByCode(item.To).Localized;
                }

                onlineDictsBindingSource.Add(item);
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (Utilities.Is(keyData, Keys.A | Keys.Control) && this.grid.Focused)
            {
                this.grid.SelectAll();
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void Download()
        {
            DialogResult = DialogResult.OK;

            Close();
        }

        private IEnumerable<DataGridViewRow> GetSelectedRows()
        {
            return grid.SelectedCells.Cast<DataGridViewCell>().Select(x => grid.Rows[x.RowIndex]).Where(x => !x.IsNewRow).Distinct();
        }

        private IEnumerable<OnlineDictDescriptor> GetSelection()
        {
            return GetSelectedRows().Select(x => _dicts[x.Index]);
        }

        private int GetSelectionSize()
        {
            return GetSelectedRows().Count();
        }

        private void Reload()
        {
            List<WebContentDownloader<OnlineDicts, object>.Job> jobs = new List<WebContentDownloader<OnlineDicts, object>.Job>();
            jobs.Add(new WebContentDownloader<OnlineDicts, object>.Job { Link = "http://www.teachme.cz/dicts.php" });

            WebContentDownloader<OnlineDicts, object>.Download(_root, this, jobs.ToArray(), Resources.CheckingOnlineDicts, Display);
        }

        private void OnDownloadClick(object sender, EventArgs e)
        {
            if (GetSelectionSize() > 0)
            {
                Download();
            }
        }

        private void OnMenuOpening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            miDownload.Enabled = GetSelectionSize() > 0;
        }

        private void OnRefreshClick(object sender, EventArgs e)
        {
            Reload();
        }

        private void OnSelectAllClick(object sender, EventArgs e)
        {
            grid.SelectAll();
        }

        private void OnShown(object sender, EventArgs e)
        {
            Reload();
        }

        private void OnCellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (GetSelectionSize() == 1 && e.RowIndex >= 0 /*exclude header*/)
            {
                Download();
            }
        }

        private void OnSelectionChanged(object sender, EventArgs e)
        {
            bOK.Enabled = GetSelectionSize() > 0;
        }
    }
}
